package com.bing.service.impl;

import com.bing.service.MailService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送
 *
 * @author 方宗庆
 * @create 2018-01-05 13:07
 */
@Service
public class MailServiceImpl implements MailService {

    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * @Description 发送简单邮件
     * @Author 方宗庆
     * @Date 2018/1/5 14:20
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            javaMailSender.send(message);
            LOG.info("邮件已经发送");
        } catch (Exception e) {
            LOG.error("邮件发送异常", e);
        }
    }

    /**
     * @Description 发送html邮件
     * @Author 方宗庆
     * @Date 2018/1/5 14:20
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content,true);
            javaMailSender.send(mimeMessage);
            LOG.info("发送成功！");
        } catch (MessagingException e) {
            LOG.error("发送失败！",e);
        }
    }
}